package com.atguigu.tingshu.common.minio.config;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.minio.service.FileUploadService;
import com.atguigu.tingshu.common.minio.service.impl.FileUploadServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/03/13 21:14
 **/
@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio",value = "enable", havingValue = "true")
public class MinioAutoConfiguration {
    /**
     * 定义MiniOClient的Bean对象
     */
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {
        try {
            // 创建MinioClient对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                // 创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                // 判断桶是否存在
                logger.error("桶对象已经存在!!!");
            }
            return minioClient;
        } catch (Exception e) {
            logger.error("minioClient对象创建失败:{}", e.getMessage());
            throw new GuiguException(201, "创建MinioClient失败");
        }
    }

    @Bean
    public FileUploadService fileUploadService(){
        return new FileUploadServiceImpl();
    }

}
